import { useRef, useState, useEffect, useCallback } from 'react'
import {  Row, Col, DatePicker, Flex, Select, Input, Button, Space, Table, Form } from 'antd'
import { useTranslation } from 'react-i18next'
import useTable from '@/hooks/useTable'
import { useSearch } from '@/hooks/useSearch'
import { tranlateKeyMap } from '@/config/keyMap'
import { DATEFORMATE } from '@/config'
import WebIcon from '@/components/WebIcon'
import EditCarModal from './components/EditCarModal'
import useGlobalConfig from '@/hooks/useGlobalConfig'
import { carQueryPage } from '@/api/car'
const { RangePicker } = DatePicker

const Index = () => {
  const { t } = useTranslation()
  const { getCarTypes, carTypes, getCarBrands, carBrands } = useGlobalConfig()
  const { changeDate } = useSearch()
  const [showEdit, setShowEdit] = useState(false)
  const [tableDate, setTableData] = useState([])
  const [currentData, setCurrentData] = useState({})
  const FormSearch = useRef({})
  const { CAR_STATUS } = tranlateKeyMap()
  
  const { headerRef, pageRef, tableScroll, pages, initPages, setTotal, total, loading, setLoading } = useTable()
  const formTimes = useRef({
    joinTimeStart: '',
    joinTimeStartEnd: ''
  })

  const changePicker = (val) => { // 日期选择器
    const dates = changeDate(val)
    formTimes.current = {
      joinTimeStart: dates[0],
      joinTimeStartEnd: dates[1]
    }
  }

  const handleEdit = (items) => { // 编辑
    setCurrentData(items)
    setShowEdit(true)
  }
  const getTableData = useCallback(async () => {
    setLoading(true)
    const params = { ...FormSearch.current, ...pages.current }
    const res = await carQueryPage(params)
    const list = res.data?.list.map(item => ({ ...item, key: item.carId }))
    setTotal(res?.data?.total || 0)
    setTableData(list)
    setLoading(false)
  }, [pages, setTotal, setLoading])
  const columns = [
    {
      title: t('car.carId'),
      dataIndex: 'carId',
      width: 100
    },
    {
      title: t('car.carType'), // 车辆类型
      dataIndex: 'carType',
    },
    {
      title: t('car.carBrand'), // 车辆品牌
      dataIndex: 'carBrand',
      width: 120
    },
    {
      title: t('car.carModel'), // 车辆型号
      dataIndex: 'carModel',
      width: 120
    },
    {
      title: t('car.joinTime'), // 入库时间
      dataIndex: 'joinTime',
    },
    {
      title: t('car.statusFlag'), // 车辆状态
      dataIndex: 'statusFlag',
      width: 180,
      render: (val) => (
        <Flex align='center' className='status-tag' style={{ color: CAR_STATUS[val - 1].color, background: `${CAR_STATUS[val - 1].color}10`}}>
          <WebIcon name={CAR_STATUS[val - 1].icon} className='status-tag-icon'/>
          {CAR_STATUS[val - 1].label}
        </Flex>
      )
    },
    {
      title: t('car.insertTime'), // 创建时间
      dataIndex: 'insertTime',
    },
    {
      title: t('car.createUserName'), // 创建人
      dataIndex: 'createUserName',
    },
    {
      title: t('opr'),
      dataIndex: 'operation',
      fixed: 'right',
      width: 160,
      render: (_, record) => (
        <Space align='center' size={17}>
          {/* 编辑 */}
          <Button type="link" className='btn-F59' onClick={() => handleEdit(record)}>{t('edit')}</Button>
        </Space>
      )
    },
  ]
  const handleSearch = (data = {}) => {
    if (data.warehouseTimes) delete data.warehouseTimes
    pages.current = initPages
    FormSearch.current = { ...data, ...formTimes.current }
    getTableData()
  }
  useEffect(() => {
    getCarTypes()
    getCarBrands()
  }, [getCarTypes, getCarBrands])
  useEffect(() => {
    getTableData()
  }, [getTableData])
  const changePagination = (page, size) => {
    pages.current = {
      pageSize: size,
      pageNum: page
    }
    getTableData()
  }
  return <Flex className='web-admin-page' vertical='vertical' ref={pageRef}>
    <header className='web-admin-page-header' ref={headerRef}>
      <Form
        layout="vertical"
        wrapperCol={{span: 12}}
        colon={false}
        onFinish={handleSearch}
      >
      <Row gutter={24}>
        {/* 入库日期 */}
        <Col span={6} className='header-item'>
          <Form.Item name='warehouseTimes' label={t('car.joinTime')}>
            <RangePicker className='header-item-input' onChange={changePicker} format={DATEFORMATE}/>
          </Form.Item>
        </Col>
        {/* 车辆类型 */}
        <Col span={3} className='header-item'>
          <Form.Item name='carType' label={t('car.carType')}>
            <Select
              className='header-item-input'
              allowClear
              options={carTypes}
              placeholder={t('inputCarType')}
            />
          </Form.Item>
        </Col>
        {/* 车辆状态 */}
        <Col span={3} className='header-item'>
          <Form.Item name='statusFlag' label={t('car.statusFlag')}>
            <Select
              className='header-item-input'
              allowClear
              options={CAR_STATUS}
              placeholder={t('inputCarStatus')}
            />
          </Form.Item>
        </Col>
        {/* 车辆品牌 */}
        <Col span={3} className='header-item'>
          <Form.Item name='carBrand' label={t('car.carBrand')}>
            <Select
              className='header-item-input'
              allowClear
              options={carBrands}
              placeholder={t('inputCarBrand')}
            />
          </Form.Item>
        </Col>
        {/* 车辆ID */}
        <Col span={3} className='header-item'>
          <Form.Item name='id' label={t('car.carId')}>
            <Input className='header-item-input' placeholder={t('inputCarID')} allowClear />
          </Form.Item>
        </Col>
        <Col span={6} className='header-item'>
          <Form.Item>
            <Space align="end" size={16} className='header-item-btns'>
              <Button icon={<WebIcon name='add-btn'/>} type="primary" htmlType="submit">{t('search')}</Button>
              <Button icon={<WebIcon name='search-btn'/>} onClick={() => handleEdit(null)}>{t('add')}</Button>
            </Space>
          </Form.Item>
        </Col>
      </Row>
      </Form>
    </header>
    <main className='web-admin-page-main'>
      <Table className='web-admin-table' dataSource={tableDate} columns={columns} scroll={tableScroll} loading={loading} pagination={{
        onChange: changePagination,
        total,
        ...pages.current
      }}/>
    </main>
    <EditCarModal items={currentData} onOk={handleSearch} show={showEdit} onCancel={() => setShowEdit(false)}/>
  </Flex>
}
export default Index
